package com.chuyu.cy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuyu.cy.contants.PageResult;
import com.chuyu.cy.entity.domain.ChatMessage;
import com.chuyu.cy.entity.domain.Contactor;
import com.chuyu.cy.entity.domain.User;
import com.chuyu.cy.entity.vo.ContactorVO;
import com.chuyu.cy.entity.vo.MessageVO;
import com.chuyu.cy.exception.CustomException;
import com.chuyu.cy.mapper.ChatMessageMapper;
import com.chuyu.cy.mapper.ContactorMapper;
import com.chuyu.cy.mapper.UserMapper;
import com.chuyu.cy.service.ContactorService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author 周小白
* @description 针对表【contactor】的数据库操作Service实现
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ContactorServiceImpl extends ServiceImpl<ContactorMapper, Contactor>
    implements ContactorService{

    @Resource
    private ContactorMapper contactorMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ChatMessageMapper chatMessageMapper;




    /**
     * 添加联系人
     * @param contactorAId 联系人A的id
     * @param contactorBId 联系人B的id
     * @return 是否添加成功
     */
    @Override
    public Boolean addContactor(Integer contactorAId, Integer contactorBId) {
        if (contactorAId == null || contactorBId == null || contactorAId.equals(contactorBId)) {
            throw new CustomException("参数错误");
        }

        LambdaQueryWrapper<Contactor> queryWrapper = new LambdaQueryWrapper<>();

        Contactor contactor = new Contactor();
        if (contactorAId < contactorBId) {
            queryWrapper.eq(Contactor::getContactorAId, contactorAId)
                .eq(Contactor::getContactorBId, contactorBId);
            Contactor exist = contactorMapper.selectOne(queryWrapper);
            if (exist != null) {
                throw new CustomException("联系人已存在");
            }

            contactor.setContactorAId(contactorAId);
            contactor.setContactorBId(contactorBId);
        } else {
            queryWrapper.eq(Contactor::getContactorAId, contactorBId)
                .eq(Contactor::getContactorBId, contactorAId);
            Contactor exist = contactorMapper.selectOne(queryWrapper);
            if (exist != null) {
                throw new CustomException("联系人已存在");
            }

            contactor.setContactorAId(contactorBId);
            contactor.setContactorBId(contactorAId);
        }

        int inserted = contactorMapper.insert(contactor);
        if (inserted != 1) {
            throw new CustomException("添加联系人失败");
        }

        return true;
    }




    /**
     * 获取联系人列表
     * @param userId 用户id
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return Result
     */
    @Override
    public PageResult<ContactorVO> getContactorList(Integer userId, Integer pageNum, Integer pageSize) {
        if (userId == null || pageNum == null || pageSize == null) {
            throw new CustomException("参数错误");
        }

        PageResult<ContactorVO> pageResult = new PageResult<>();

        // 获取联系人列表
        Integer pageStart = (pageNum - 1) * pageSize;
        List<Contactor> contactors = contactorMapper.getContactorList(userId, pageStart, pageSize);

        ArrayList<ContactorVO> contactorList = new ArrayList<>();
        // 封装联系人信息
        for (Contactor item : contactors) {
            if (userId.equals(item.getContactorAId())) {
                User user = userMapper.selectById(item.getContactorBId());
                if (user == null) {
                    continue;
                }
                ContactorVO contactorVO = new ContactorVO();
                contactorVO.setId(user.getId());
                contactorVO.setNickName(user.getNickName());
                contactorVO.setAvatar(user.getAvatar());

                // 获取最新消息
                LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ChatMessage::getSenderId, user.getId())
                    .eq(ChatMessage::getReceiverId, userId)
                            .or()
                    .eq(ChatMessage::getSenderId, userId)
                    .eq(ChatMessage::getReceiverId, user.getId())
                    .orderByDesc(ChatMessage::getCreateTime);
                List<ChatMessage> chatMessageList = chatMessageMapper.selectList(queryWrapper);
                // 如果没有聊天消息
                if (CollectionUtil.isEmpty(chatMessageList)) {
                    contactorList.add(contactorVO);
                    continue;
                }

                ChatMessage chatMessage = chatMessageList.get(0);
                if (chatMessage != null) {
                    MessageVO messageVO = BeanUtil.copyProperties(chatMessage, MessageVO.class);

                    contactorVO.setMessageVO(messageVO);
                }

                contactorList.add(contactorVO);
            } else {
                User user = userMapper.selectById(item.getContactorAId());
                if (user == null) {
                    continue;
                }
                ContactorVO contactorVO = new ContactorVO();
                contactorVO.setId(user.getId());
                contactorVO.setNickName(user.getNickName());
                contactorVO.setAvatar(user.getAvatar());

                // 获取最新消息
                LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ChatMessage::getSenderId, user.getId())
                        .eq(ChatMessage::getReceiverId, userId)
                        .or()
                        .eq(ChatMessage::getSenderId, userId)
                        .eq(ChatMessage::getReceiverId, user.getId())
                        .orderByDesc(ChatMessage::getCreateTime);
                List<ChatMessage> chatMessageList = chatMessageMapper.selectList(queryWrapper);
                // 如果没有聊天消息
                if (CollectionUtil.isEmpty(chatMessageList)) {
                    contactorList.add(contactorVO);
                    continue;
                }

                ChatMessage chatMessage = chatMessageList.get(0);
                if (chatMessage != null) {
                    MessageVO messageVO = BeanUtil.copyProperties(chatMessage, MessageVO.class);

                    contactorVO.setMessageVO(messageVO);
                }

                contactorList.add(contactorVO);
            }
        }

        pageResult.setList(contactorList);

        return pageResult;
    }




    /**
     * 删除联系人
     * @param userId 用户id
     * @param contactorId 联系人id
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteContactor(Integer userId, Integer contactorId) {
        if (userId == null || contactorId == null || userId.equals(contactorId)) {
            throw new CustomException("参数错误");
        }

        LambdaQueryWrapper<Contactor> queryWrapper = new LambdaQueryWrapper<>();
        if (userId < contactorId) {
            queryWrapper.eq(Contactor::getContactorAId, userId)
                .eq(Contactor::getContactorBId, contactorId);
            Contactor contactor = contactorMapper.selectOne(queryWrapper);
            if (contactor == null) {
                throw new CustomException("联系人已经不存在");
            }

            int deleted = contactorMapper.deleteById(contactor.getId());
            if (deleted == 0) {
                throw new CustomException("删除联系人失败");
            }
        } else {
            queryWrapper.eq(Contactor::getContactorAId, contactorId)
                .eq(Contactor::getContactorBId, userId);
            Contactor contactor = contactorMapper.selectOne(queryWrapper);
            if (contactor == null) {
                throw new CustomException("联系人已经不存在");
            }

            int deleted = contactorMapper.deleteById(contactor.getId());
            if (deleted == 0) {
                throw new CustomException("删除联系人失败");
            }
        }

        return true;
    }
}




